package com.hyacinth.forumbite.service.impl;

import cn.hutool.core.date.DateUtil;
import com.hyacinth.forumbite.config.MinioConfig;
import com.hyacinth.forumbite.dao.UserMapper;
import com.hyacinth.forumbite.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioClient minioClient;

    @Resource
    private UserMapper userMapper;

    @Override
    public String upload(MultipartFile file, Long userId) {
        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();

            // 创建bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucket()).build());

            // 如果不存在，那么此时就创建一个新的桶
            // 如果存在打印信息
            if (!found)
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucket()).build());
            else System.out.println("Bucket " + minioConfig.getBucket() + "already exists.");


            // 设置存储对象名称(唯一)
            String fileName = file.getOriginalFilename();
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 最终的文件名称
            fileName = dateDir + "/" + uuid + fileName;
            System.out.println("fileName : " + fileName);
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucket())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .build();
            minioClient.putObject(putObjectArgs);

            // minio上传图片路径:http://localhost:9000/xitao-bucket/Redis.png

            String url = minioConfig.getEndpoint() + "/" + minioConfig.getBucket() + "/" + fileName;
            System.out.println(url);

            // 修改用户头像路径
            userMapper.updateUserAvatarUrl(url, userId);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
